package com.manong.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.manong.domain.Permission;
import com.manong.exception.BusinessExp;
import com.manong.mapper.PermissionMapper;
import com.manong.query.QueryObject;
import com.manong.service.IPermissionService;
import com.manong.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {

    private PermissionMapper permissionMapper;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private RequestMappingInfoHandlerMapping requestMappingInfoHandlerMapping;

    @Autowired
    public void setPermissionMapper(PermissionMapper permissionMapper) {
        this.permissionMapper = permissionMapper;
    }

    @Override
    public PageInfo query(QueryObject qo) {
        // 判断 pageSize 是否为 -1
        if (qo.getPageSize() == -1) {
            // 查询全部数据
            List<Permission> permissions = permissionMapper.selectForList();
            // 返回分页信息，此时 total 为全部数据的数量
            return new PageInfo(permissions);
        } else {
            // 正常分页操作
            // 告诉 PageHelper 当前页是多少，每页显示多少条数据
            PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
            // 调用分页方法
            List<Permission> permissions = permissionMapper.selectForList();
            return new PageInfo(permissions);
        }
    }

    /**
     * 加载权限
     */
    @Override
    public void load() {
        // 拿到已有的权限
        List<String> expressions = permissionMapper.selectExpression();
        // 从spring容器中获取所有controller
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(RestController.class);
        Collection<Object> values = beansWithAnnotation.values();
        // 遍历所有controller
        for (Object value : values) {
            // 通过controller去拿controller中所有的方法
            Method[] declaredMethods = value.getClass().getDeclaredMethods();
            for (Method declaredMethod : declaredMethods) {
                // 在通过方法去那方法上自定义注解@RequiredPermission
                RequiredPermission annotation = declaredMethod.getAnnotation(RequiredPermission.class);
                // 判断是否为空
                if(annotation != null) {
                    // 不为空把注解中name和expression表达式取出来
                    String name = annotation.name();
                    String expression = annotation.expression();
                    // 数据库中不存在的权限，才插入
                    if(!expressions.contains(expression)) {
                        // 创建permission，把name和expression封装到permission对象中
                        Permission permission = new Permission();
                        permission.setName(name);
                        permission.setExpression(expression);
                        // 插入到数据库中
                        permissionMapper.insert(permission);
                    }
                }
            }
        }
    }

    /**
     * 根据角色id查询拥有权限集合
     *
     * @param id
     * @return
     */
    @Override
    public List<Permission> queryByPermission(Long id) {
        // 参数校验
        if(id == null) {
            throw new BusinessExp("非法操作");
        }
        return permissionMapper.queryByPermission(id);
    }

    /**
     * 加载权限-改
     */
    public void loadPlus(){
        // 拿到已有的权限
        List<String> expressions = permissionMapper.selectExpression();
        // 通过处理器映射器去拿所有HandlerMethod，HandlerMethod封装我们方法信息
        // 在启动的时候会把控制器中方法封装到HandlerMethod中
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingInfoHandlerMapping.getHandlerMethods();
        // 拿到方法集合
        Collection<HandlerMethod> values = handlerMethods.values();
        for (HandlerMethod value : values) {
            Method method = value.getMethod();
            // 通过controller去拿controller中所有的方法
            Method[] declaredMethods = method.getClass().getDeclaredMethods();
            for (Method declaredMethod : declaredMethods) {
                // 在通过方法去那方法上自定义注解@RequiredPermission
                RequiredPermission annotation = declaredMethod.getAnnotation(RequiredPermission.class);
                // 判断是否为空
                if(annotation != null) {
                    // 不为空把注解中name和expression表达式取出来
                    String name = annotation.name();
                    String expression = annotation.expression();
                    // 数据库中不存在的权限，才插入
                    if(!expressions.contains(expression)) {
                        // 创建permission，把name和expression封装到permission对象中
                        Permission permission = new Permission();
                        permission.setName(name);
                        permission.setExpression(expression);
                        // 插入到数据库中
                        permissionMapper.insert(permission);
                    }
                }
            }
        }
    }
}
